<?php
/**
 * 账号运营情况控制器
 */
namespace Beerus\Modules\DesignerInfoLib\Controllers;

use App\Http\Controllers\Controller;
use Doraemon\model\DesignerInfoLib\OperateInfo as mOperateInfo;
use Doraemon\model\{Article as mArticle, DesignerInfoLib\OperateLog as mOperateLog, Photos as mPhotos};
use Doraemon\model\Operator as mOperator;
use Doraemon\model\DesignerAuth as mDesignerAuth;
use Encore\Admin\Facades\Admin;
use Hhz\AdministrativeRegion\Region;
use Illuminate\Http\Request;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Widgets\Tab;
use Doraemon\pockets\constInterface\DesignerInfoLib\OperateInfo as iOperateInfo;
use Doraemon\model\DesignerInfoLib\DesignerOperateHelpPageDay as mDesignerOperateHelpPageDay;
use Doraemon\model\Designer\NewDesignerConsultFeedBack as mNewDesignerConsultFeedBack;
use Doraemon\model\DesignerRanking\DesignerRanking as mDesignerRanking;
use Doraemon\model\Designer\DesignerAnnual as mDesignerAnnual;
use Doraemon\model\ReDesignerCompetition\DcHonorArticle as mDcHonorArticle;
use Doraemon\model\DesignerCompetition\DcHonor as mDcHonor;
use Doraemon\model\Designer\DesignerViolationRecord as mDesignerViolationRecord;
use Doraemon\model\Designer\DesignerRecommendScore as mDesignerRecommendScore;
use Doraemon\model\Elasticsearch\Photo as esPhotoModel;

class OperationController extends Controller implements iOperateInfo {

    const PAGE_SIZE = 5;
    const LT_50 = 1;
    const GT_50 = 2;
    const LT_3 = 1;
    const GT_3 = 2;
    // beerus后台筛选
    const YES_OR_NO_OPTIONS = [
        0 => '全部',
        self::OPTION_NO => '否',
        self::OPTION_YES => '是'
    ];
    const HIGH_RATE_OPTIONS = [
        0 => '全部',
        self::LT_50 => '低于50%',
        self::GT_50 => '高于等于50%'
    ];
    const SCORE_OPTIONS = [
        0 => '全部',
        self::LT_3 => '小于3',
        self::GT_3 => '大于等于3'
    ];

    // 账号运营辅导列表
    public function index(Request $request, Content $content) {
        $params = $request->all();
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);

        $condition = self::buildCondition($params);
        $condition['auth_status'] = self::AUTH_STATUS_ONLINE;
        $total = mOperateInfo::count($condition);
        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];
        $lists = mOperateInfo::select('*', $condition);

        $operatorList = mOperator::getOperatorWithShowNameList();
        $operators = array_combine(array_column($operatorList, 'id'), array_column($operatorList, 'operator_show_name'));
        $operators[0] = '未绑定运营';

        self::formatList($lists);

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);

        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $operators) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableActions();
                $grid->disableCreateButton();

                $grid->filter(function (Grid\Filter $filter) use ($operators) {
                    $filter->disableIdFilter();

                    $filter->column(1 / 3, function ($filter) use ($operators) {
                        $filter->equal('keyword', 'UID/昵称')->placeholder('请输入uid或者昵称');
                        $filter->in('main_area_code', '地区(多选)')->multipleSelect(Region::getProvincesList());
                        $filter->in('operator_id', '对接运营(多选)')->multipleSelect($operators);
                        $filter->equal('is_violation', '违规处罚记录')->select(self::YES_OR_NO_OPTIONS);
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('article_high_rate', '整屋优质率')->select(self::HIGH_RATE_OPTIONS);
                        $filter->equal('note_high_rate', '动态优质率')->select(self::HIGH_RATE_OPTIONS);
                        $filter->equal('designer_evaluation_score', '口碑评分')->select(self::SCORE_OPTIONS);
                        $filter->equal('bind_designer_article_num', '业主晒家')->select(self::SCORE_OPTIONS);
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->year('month_list', '月榜');
                        $filter->year('annual_list', '年榜');
                        $filter->equal('is_dc_award', '营造家奖')->select(self::YES_OR_NO_OPTIONS);
                        $filter->equal('is_future', 'Future私宅坐标人物')->select(self::YES_OR_NO_OPTIONS);
                    });

                    $filter->expand();
                });
                $grid->column('uid', 'UID')->width(80);
                $grid->column('user_info', '用户基础信息')->display(function () use ($operators) {
                    $userInfo = [
                        '<strong>[&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;昵称&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;]: </strong>' . $this->nick,
                        '<strong>[对&nbsp;&nbsp;&nbsp;接&nbsp;&nbsp;&nbsp;运&nbsp;&nbsp;&nbsp;&nbsp;营]: </strong>' . $operators[$this->operator_id],
                        '<strong>[认&nbsp;&nbsp;&nbsp;证&nbsp;&nbsp;&nbsp;类&nbsp;&nbsp;&nbsp;&nbsp;型]: </strong>' . mDesignerAuth::DESIGNER_TYPE[$this->auth_type],
                        '<strong>[累计认证时长]: </strong>' . number_format($this->total_auth_year/10, 1) . '年',
                        '<strong>[主要服务地区]: </strong>' . $this->main_area_name ?? '未设置',
                        '<strong>[认证到期时间]: </strong>' . date('Y-m-d H:i:s', $this->auth_end_time),
                    ];
                    return implode("<br>", $userInfo);
                })->width(180);
                $grid->column('consult_info', '咨询数据')->display(function () {
                    $consultInfo = [
                        "<strong>[最新认证周期内咨询总数]: </strong><a href='https://frieza.haohaozhu.me/admin/im/msg_list?&from_user_group=0&to_user_group=0&to_user={$this->uid}' style='text-decoration: underline'>".$this->auth_consult_cnt."</a>",
                        '<strong>[近7天咨询数]: </strong>' . $this->seven_consult_cnt,
                        '<strong>[认证周期内待运营跟进的二级有效咨询数]: </strong>' . $this->sign_operate_cnt,
                    ];
                    return implode("<br>", $consultInfo);
                })->width(220);
                $grid->column('article_publish_info', '整屋发布情况')->display(function () {
                    $consultInfo = [
                        '<strong>[整屋发布总数]: </strong>' . $this->publish_article_cnt,
                        '<strong>[认证周期內整屋发布数]: </strong>' . $this->auth_publish_article_cnt,
                        '<strong>[认证周期內整屋优质率]: </strong>' . $this->article_high_rate .'%',
                        '<strong>[最后一次发布整屋时间]: </strong>' . $this->last_article_publish_time,
                    ];
                    return implode("<br>", $consultInfo);
                })->width(200);
                $grid->column('note_publish_info', '动态发布情况')->display(function () {
                    $consultInfo = [
                        '<strong>[动态发布总数]: </strong>' . $this->publish_note_cnt,
                        '<strong>[认证周期內动态发布数]: </strong>' . $this->auth_publish_note_cnt,
                        '<strong>[挂话题的note]: </strong>' . $this->topic_note_cnt,
                        '<strong>[认证周期內动态优质率]: </strong>' . $this->note_high_rate .'%',
                        '<strong>[最后一次发布动态时间]: </strong>' . $this->last_note_publish_time,
                    ];
                    return implode("<br>", $consultInfo);
                })->width(200);
                $grid->column('month_rank_info', '历史上月榜情况')->display(function () {
                    $monthRankInfo = $this->month_rank_info ? implode("<br>", $this->month_rank_info) : '无';
                    return '<div style="height: 150px;overflow: scroll">'.$monthRankInfo.'</div>';
                })->width(200);
                $grid->column('annual_rank_info', '历史上年榜情况')->display(function () {
                    $annualRankInfo = $this->annual_rank_info ? implode("<br>", array_map(function ($value) {
                        return $value . '年年榜';
                    }, $this->annual_rank_info)) : '无';
                    return '<div style="height: 150px;overflow: scroll">'.$annualRankInfo.'</div>';
                })->width(200);
                $grid->column('dc_award_info', '营造家奖')->display(function () {
                    $dcAwardInfo = $this->dc_award_info ? implode("<br>", $this->dc_award_info) : '无';
                    return '<div style="height: 150px;overflow: scroll">'.$dcAwardInfo.'</div>';
                })->width(200);
                $grid->column('other_info', '其他信息')->display(function () {
                    $consultInfo = [
                        '<strong>[推荐指数]: </strong>' . $this->recommend_score,
                        "<strong>[口碑评分]: </strong><a href='/admin/Designer/evaluation?to_user={$this->uid}' style='text-decoration: underline'>".$this->designer_evaluation_score."</a>",
                        '<strong>[业主晒家数]: </strong>' . $this->bind_designer_article_num,
                        "<strong>[违规记录数]: </strong><a href='/admin/Violation/designer?designer_uid={$this->uid}' style='text-decoration: underline'>".$this->violation_cnt."</a>",
                        '<strong>[Future私宅坐标人物]: </strong>' . ($this->is_future == self::OPTION_YES ? '是' : '否'),
                    ];
                    return implode("<br>", $consultInfo);
                })->width(200);
                $grid->column('is_multiple_accounts', '是否多账号(可编辑)')
                    ->select(self::YES_OR_NO_OPTIONS)
                    ->width(100);
            }
        );

        $tab = new Tab();
        $tab->add('账号运营情况', $gridList->render());
        $content->row($tab);
        return $content
            ->header('账号运营情况')
            ->breadcrumb(['text' => '设计师运营信息库'], ['text' => '账号运营情况']);
    }

    public static function buildCondition($params) {
        $condition = [];
        // uid/昵称
        if (!empty($params['keyword'])) {
            if (is_numeric($params['keyword'])) {
                $condition['uid'] = $params['keyword'];
            } else {
                $condition['nick[~]'] = $params['keyword'];
            }
        }
        // 地区，多选
        if (!empty($params['main_area_code'])) {
            $mainAreaCode = array_filter($params['main_area_code']);
            if (!empty($mainAreaCode)) {
                $condition['main_area_code'] = $params['main_area_code'];
            }
        }
        // 对接运营
        if (!empty($params['operator_id'])) {
            $operatorId = array_filter($params['operator_id']);
            if (!empty($operatorId)) {
                $condition['operator_id'] = $params['operator_id'];
            }
        }
        // 是否有违规记录
        if (!empty($params['is_violation'])) {
            $condition['is_violation'] = $params['is_violation'];
        }
        // 整屋优质率
        if (!empty($params['article_high_rate'])) {
            $op = $params['article_high_rate'] == self::LT_50 ? '[<]' : '[>=]';
            $condition["article_high_rate{$op}"] = 50;
        }
        // 动态优质率
        if (!empty($params['note_high_rate'])) {
            $op = $params['note_high_rate'] == self::LT_50 ? '[<]' : '[>=]';
            $condition["note_high_rate{$op}"] = 50;
        }
        // 口碑评分
        if (!empty($params['designer_evaluation_score'])) {
            $op = $params['designer_evaluation_score'] == self::LT_3 ? '[<]' : '[>=]';
            $condition["designer_evaluation_score{$op}"] = 3;
        }
        // 业主晒家数量
        if (!empty($params['bind_designer_article_num'])) {
            $op = $params['bind_designer_article_num'] == self::LT_3 ? '[<]' : '[>=]';
            $condition["bind_designer_article_num{$op}"] = 3;
        }
        // 月榜
        if (!empty($params['month_list'])) {
            $condition['month_list[~]'] = $params['month_list'];
        }
        // 年榜
        if (!empty($params['annual_list'])) {
            $condition['annual_list[~]'] = $params['annual_list'];
        }
        // 营造家奖
        if (!empty($params['is_dc_award'])) {
            $condition['is_dc_award'] = $params['is_dc_award'];
        }
        // 私宅坐标任务
        if (!empty($params['is_future'])) {
            $condition['is_future'] = $params['is_future'];
        }
        return $condition;
    }

    public static function formatList(&$list) {
        //
        foreach ($list as &$item) {
            // 获取咨询数据
            $userLatestData = mDesignerOperateHelpPageDay::getListByIdentityTime($item['uid'], $item['auth_start_time']);
            // 最新认证周期內咨询总数
            $item['auth_consult_cnt'] = array_sum(array_column($userLatestData, 'consult_cnt'));;
            // 近7天咨询数
            array_multisort(array_column($userLatestData, 'day'), SORT_DESC, $userLatestData);
            $sevenList = array_slice($userLatestData, 0, 7);
            $item['seven_consult_cnt'] = array_sum(array_column($sevenList, 'consult_cnt'));
            // 认证周期内待运营跟进的二级有效咨询数
            $item['sign_operate_cnt'] = mNewDesignerConsultFeedBack::countNeedSignOperateListByAuthTime($item['uid'], $item['auth_start_time'], $item['auth_end_time']);
            // 认证周期內整屋发布数
            $item['auth_publish_article_cnt'] = mArticle::getPublishArticleCntByAuthTime($item['uid'], $item['auth_start_time'], $item['auth_end_time']);
            // 整屋发布总数
            $item['publish_article_cnt'] = mArticle::getPublishCanSeeCountByUid($item['uid']);
            // 最后一次发布整屋时间
            $item['last_article_publish_time'] = ($ret = mArticle::getLatestArticle($item['uid'])) ? date('Y-m-d H:i:s', $ret['publish_time']) : '无';
            // 认证周期内动态发布数
            $item['auth_publish_note_cnt'] = mPhotos::getPublishNoteCntByAuthTime($item['uid'], $item['auth_start_time'], $item['auth_end_time']);
            // 挂话题的note
            $esPhotoModel = new esPhotoModel();
            $where = [
                'AND' => [
                    'uid' => $item['uid'],
                    'show_status' => mPhotos::SHOW_STATUS_NORMAL_DISTRIBUTION,
                    'show_type' => mPhotos::SHOW_TYPE_PIC,
                ],
                'LIMIT' => 1
            ];
            $answerCount = $esPhotoModel->search($where, '*', true);
            $item['topic_note_cnt'] = $answerCount['total'] ?? 0;
            // 动态发布总数
            $excludeNoteCnt = 0;
            $noteRet = mPhotos::getPublishNoteList($item['uid']);
            if (!empty($noteRet)) {
                $noteIds = array_column($noteRet, 'id');
                $excludeNoteCnt = \Doraemon\model\AdmNoteRemark::count('*', ['note_id' => $noteIds, 'remark' => ['疑似违规','二次审核-描述修改','二次审核-新增图片']]);
            }
            $item['publish_note_cnt'] = (count($noteRet) - $excludeNoteCnt) ?? 0;
            // 最后一次发布动态时间
            $item['last_note_publish_time'] = ($ret = mPhotos::getLatestNote($item['uid'])) ? date('Y-m-d H:i:s', $ret['addtime']) : '无';
            // 历史上月榜情况
            $monthRankingList = mDesignerRanking::getHistoryRankingListByUid($item['uid']);
            $monthRankingData = [];
            foreach ($monthRankingList as $rankingItem) {
                $monthRankingData[$rankingItem['ranking_month']][] = $rankingItem['sub_ranking_name'];
            }
            $monthRanking = [];
            if (!empty($monthRankingData)) {
                foreach ($monthRankingData as $month => $monthRankingDataItem) {
                    $monthRanking[] = $month . ' ' . implode('、', $monthRankingDataItem);
                }
            }
            $item['month_rank_info'] = $monthRanking;
            // 历史上年榜情况
            $item['annual_rank_info'] = mDesignerAnnual::getUserAllYear($item['uid']);
            // 营造家奖
            $dcHonorData = [];
            $dcHonorList = mDcHonorArticle::getAllHonorList($item['uid']);
            foreach ($dcHonorList as $honorItem) {
                $dcHonorData[$honorItem['dc_year']] = $dcHonorData[$honorItem['dc_year']] ?? [];
                $dcHonorData[$honorItem['dc_year']] = array_unique(array_merge($dcHonorData[$honorItem['dc_year']], explode('、', $honorItem['honor_ids'])));
            }
            $dcHonor = [];
            if (!empty($dcHonorData)) {
                foreach ($dcHonorData as $year => $dcHonorIds) {
                    $honorList = mDcHonor::select('*', ['id' => $dcHonorIds]);
                    $honorNames = array_column($honorList, 'honor_name');
                    $dcHonor[] = $year . ' ' . implode('、', $honorNames);
                }
            }
            $item['dc_award_info'] = $dcHonor;
            // 推荐指数
            $item['recommend_score'] = mDesignerRecommendScore::getAuthLastScoreBetweenDay($item['uid'], date('Ymd', $item['auth_start_time']), date('Ymd', $item['auth_end_time'])) ?? 0;
            // 违规记录数
            $item['violation_cnt'] = mDesignerViolationRecord::getViolationCnt($item['uid']);
        }
    }

    public function save(Request $request, $id) {
        $isMultipleAccounts = $request->input('is_multiple_accounts', '');
        $operateInfo = mOperateInfo::getInfoById($id);
        if (empty($operateInfo)) {
            return response()->json([
                'status' => false,
                'message' => '运营信息不存在～'
            ]);
        }
        if ($operateInfo['is_multiple_accounts'] == $isMultipleAccounts) {
            return response()->json([
                'status' => false,
                'message' => '无变化～'
            ]);
        }
        if (!mOperateInfo::updateIsMultipleAccounts($id, $isMultipleAccounts)) {
            return response()->json([
                'status' => false,
                'message' => '更新多账号失败～'
            ]);
        }
        // 写入运营操作日志,无需判断日志是否写入成功
        mOperateLog::addLog($operateInfo['id'], self::OPER_ACTION_ASSOC_TYPE_MULTIPLE_ACCOUNTS, $operateInfo['is_multiple_accounts'], $isMultipleAccounts, Admin::user()->id);
        return response()->json([
            'status' => true,
            'message' => '修改成功～'
        ]);
    }
}